﻿using MyWeb.Model.Models;
using MyWeb.Model.User;
using MyWeb.Repository.Base;
using MyWeb.Services.Base;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MyWeb.Services
{
    /// <summary>
    /// sysUserInfoServices
    /// </summary>	
    public class SysUserInfoServices : ISysUserInfoServices
    {
        private readonly IBaseRepository<UserRole> _userRoleRepository;
        private readonly IBaseRepository<Role> _roleRepository;
        private readonly IBaseRepository<SysUserInfo> BaseDal;
        public SysUserInfoServices(IBaseRepository<UserRole> userRoleRepository, IBaseRepository<Role> roleRepository, IBaseRepository<SysUserInfo> baseDal)
        {
            _userRoleRepository = userRoleRepository;
            _roleRepository = roleRepository;
            this.BaseDal = baseDal;
        }
        /// <summary>
        /// 根据用户名和密码获取用户信息
        /// </summary>
        /// <param name="loginName">用户名</param>
        /// <param name="loginPwd">密码</param>
        /// <returns></returns>
        public async Task<SysUserInfo?> SaveUserInfo(string loginName, string loginPwd)
        {
            SysUserInfo sysUserInfo = new SysUserInfo(loginName, loginPwd);
            SysUserInfo? model = new SysUserInfo();
            var userList = await BaseDal.Query(a => a.LoginName == sysUserInfo.LoginName && a.LoginPWD == sysUserInfo.LoginPWD);
            if (userList.Count > 0)
            {
                model = userList.FirstOrDefault();
            }
            else
            {
                var id = await BaseDal.Add(sysUserInfo);
                model = await BaseDal.QueryById(id);
            }

            return model;

        }

        /// <summary>
        /// 根据用户名和密码获取用户角色权限信息
        /// </summary>
        /// <param name="loginName">用户名</param>
        /// <param name="loginPwd">密码</param>
        /// <returns></returns>
        public async Task<string> GetUserRoleNameStr(string loginName, string loginPwd)
        {
            string roleName = "";
            var user = (await BaseDal.Query(a => a.LoginName == loginName && a.LoginPWD == loginPwd)).FirstOrDefault();
            var roleList = await _roleRepository.Query(a => a.IsDeleted == false);
            if (user != null)
            {
                var userRoles = await _userRoleRepository.Query(ur => ur.UserId == user.Id);
                if (userRoles.Count > 0)
                {
                    var arr = userRoles.Select(ur => ur.RoleId.ToString()).ToList();
                    var roles = roleList.Where(d => arr.Contains(d.Id.ToString()));

                    roleName = string.Join(',', roles.Select(r => r.Name).ToArray());
                }
            }
            return roleName;
        }
    }
}
